package srv

import (
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/app/ginsrv/api/base"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/app/sysparam"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/columnd"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/factory"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/infod"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/interactiond"
)

func createCtrl(d core.CmsDomain) *myctrl {
	return &myctrl{
		BaseContrl: base.BaseContrl{
			Domain: d,
		},
		iiar: d.Interaction().InteractionAggregateRoot(),
		iar:  d.Info().InfoAggregateRoot(),
		car:  d.Column().ColumnAggregateRoot(),
	}
}

type respMyNums struct {
	Follows int `json:"follows"`
	Fans    int `json:"fans"`
	Coll    int `json:"coll"`
	Ints    int `json:"ints"`
}
type myctrl struct {
	base.BaseContrl
	iar  infod.InfoAggregateRoot
	iiar interactiond.InteractionAggregateRoot
	car  columnd.ColumnAggregateRoot
}

func (c myctrl) getColumn(ctx *gin.Context) {
	columnid := ctx.Param("columnid")
	if columnid == "" {
		c.ErrBadRequest(ctx, 1, "参数错误")
		return
	}
	dctx := c.DDDContext(ctx)
	col, err := c.car.GetColumn(dctx, columnid)
	if err != nil {
		c.ErrServerError(ctx, 2, "查询失败", err)
		return
	}
	c.Success(ctx, col)
	return
}

func (c myctrl) queryMyNums(ctx *gin.Context) {
	intsColumnid := sysparam.IntsColumnid()
	dctx := c.DDDContext(ctx)
	uid := ctx.Param("uid")
	if uid == "" {
		c.ErrUnauthorized(ctx, "查询失败：未登录")
		return
	}
	code := sysparam.IntsFollowCode()

	// 用户的粉丝数　用户关注数
	g, err := factory.DefaultFactory.GetOrCreIGroup(dctx, interactiond.IGTTPerson, uid)
	if err != nil {
		c.ErrServerError(ctx, 2, "查询失败", errors.Wrapf(err, "查询或创建互动组信息失败"))
		return
	}
	resp := respMyNums{}
	// 获取粉丝数
	for _, v := range g.GroupTotal {
		switch v.ITCode {
		case code:
			resp.Fans = v.Total
			// case intTypeCollCode:
			// 	resp.Coll = v.Total
		}
	}
	// 获取关注数
	if resp.Follows, err = c.iiar.QueryNum(dctx, interactiond.InteractionSearch{
		Codes: []string{code},
		UID:   []string{uid},
	}); err != nil {
		c.ErrServerError(ctx, 3, "查询失败", errors.Wrapf(err, "查询%v粉丝数失败", uid))
		return
	}
	// 获取收藏
	if resp.Coll, err = c.iiar.QueryNum(dctx, interactiond.InteractionSearch{
		Codes: []string{sysparam.IntsCollectionCode()},
		UID:   []string{uid},
	}); err != nil {
		c.ErrServerError(ctx, 3, "查询失败", errors.Wrapf(err, "查询%v粉丝数失败", uid))
		return
	}
	if resp.Ints, err = c.iar.QueryNum(dctx, infod.InfoSearch{
		ColumnID: intsColumnid,
		Creator:  uid,
		Status:   []infod.IStatus{infod.IStatusPublished},
	}); err != nil {
		c.ErrServerError(ctx, 4, "查询失败", errors.Wrapf(err, "查询%v互动数量失败", uid))
		return
	}
	c.Success(ctx, resp)
}
